package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.xn.app.muying.R;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.JSONUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.ToastUtil;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class DengLuActivity extends AppCompatActivity {
    EditText zhanghao, mima;
    Button denglu;
    TextView wangji, zhuce;
    private ScrollView scrollview = null;
    OkHttpClient mOkHttpClient = null;
    //是否显示密码
    private ImageView open_close = null;
    //数据库
    private DBManager db = null;
    //记录点击状态
    private boolean lean = false;
    //记录当前点击的是账号还是密码
    private int i = 0;
    //接收调用登录功能的页面信息
    private Intent intent=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //如果手机系统大于等于5.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.BLACK);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //如果手机系统大于等于4.4并且小于等于5.0
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_deng_lu);
        db = new DBManager(this);
        mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS).build();
        scrollview = (ScrollView) findViewById(R.id.scrollview);
        scrollview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                return true;
            }
        });
        zhanghao = (EditText) findViewById(R.id.zhang_hao);
        zhanghao.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    i = 1;
                }
            }
        });
        mima = (EditText) findViewById(R.id.mi_ma);
        mima.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    i = 2;
                }
            }
        });
        open_close = (ImageView) findViewById(R.id.open_close);
        denglu = (Button) findViewById(R.id.deng_lu);
        wangji = (TextView) findViewById(R.id.wang_ji);
        zhuce = (TextView) findViewById(R.id.zhu_ce);
        denglu.setOnClickListener(onClickListener);
        zhanghao.setOnClickListener(onClickListener);
        mima.setOnClickListener(onClickListener);
        wangji.setOnClickListener(onClickListener);
        zhuce.setOnClickListener(onClickListener);
        open_close.setOnClickListener(onClickListener);
        zhanghao.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            //当键盘弹出隐藏的时候会 调用此方法。
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                //获取当前界面可视部分
                DengLuActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                //获取屏幕的高度
                int screenHeight = DengLuActivity.this.getWindow().getDecorView().getRootView().getHeight();
                //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                int heightDifference = screenHeight - r.bottom;
                //重新计算scrollview高度
                LinearLayout.LayoutParams layoutParams= (LinearLayout.LayoutParams) scrollview.getLayoutParams();
                layoutParams.setMargins(0,0,0,heightDifference);//设置ScrollView的marginBottom的值为软键盘占有的高度即可
                scrollview.requestLayout();
                if (heightDifference > 0) {

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            scrollview.fullScroll(ScrollView.FOCUS_DOWN);
                            if (i == 1) {
                                zhanghao.setFocusable(true);
                                zhanghao.setFocusableInTouchMode(true);
                                zhanghao.requestFocus();
                                zhanghao.findFocus();
                            } else if (i == 2) {
                                mima.setFocusable(true);
                                mima.setFocusableInTouchMode(true);
                                mima.requestFocus();
                                mima.findFocus();
                            }
                        }
                    });
                }
            }

        });
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                //登陆
                case R.id.deng_lu:
                    String zh = zhanghao.getText().toString();
                    String mm = mima.getText().toString();
                    if (!TextUtils.isEmpty(zh) && !TextUtils.isEmpty(mm)) {
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                        denglu(zh, mm);
                    } else {
                        ToastUtil.showToast(DengLuActivity.this, "账号和密码不能为空");
                    }
                    break;
                //忘记密码
                case R.id.wang_ji:
                    Intent intent1 = new Intent(DengLuActivity.this, YanZhengActivity.class);
                    intent1.putExtra("tag", "2");
                    startActivity(intent1);
                    break;
                //注册
                case R.id.zhu_ce:
                    Intent intent = new Intent(DengLuActivity.this, YanZhengActivity.class);
                    intent.putExtra("tag", "0");
                    startActivity(intent);
                    break;
                //是否显示密码
                case R.id.open_close:
                    i = 2;
                    if (!lean) {
                        lean = true;
                        open_close.setImageResource(R.mipmap.open_passworid);
                        mima.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    } else {
                        lean = false;
                        open_close.setImageResource(R.mipmap.close_password);
                        mima.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    }
                    mima.setSelection(mima.getText().length());
                    break;
                //用户名
                case R.id.zhang_hao:
                    i = 1;
                    break;
                //密码
                case R.id.mi_ma:
                    i = 2;
                    break;
            }
        }
    };

    AlertDialog denglu_dialog;

    /**
     * 登录
     *
     * @param zh 帐号
     * @param mm 密码
     */
    void denglu(final String zh, final String mm) {
        denglu_dialog = new MyAlertDialog().ShowDialog(DengLuActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    RequestBody formBody = new FormBody.Builder().add("grant_type", "password")
                            .add("username", zh).add("password", mm)
                            .build();
                    String p = "grant_type=password  username=" + zh + "  password" + mm;
                    Request request = new Request.Builder().url(APIMethod.DengLu).post(formBody).build();
                    okhttp3.Response response = mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    //{"error":"invalid_grant","error_description":" 登录失败，用户名或密码错误！"}
                    if (code == 200) {
                        //获取用户数据
                        JSONObject jsonObject = new JSONObject(bodys);
                        //添加用户数据
                        db.insertUser(jsonObject.get("access_token").toString(), jsonObject.get("token_type").toString(), jsonObject.get("userName").toString());
                        Request request1 = new Request.Builder().url(APIMethod.UserInfo).addHeader("Authorization", jsonObject.get("token_type").toString() + " " + jsonObject.get("access_token").toString()).get().build();
                        okhttp3.Response response1 = MuYingApplication.mOkHttpClient.newCall(request1).execute();
                        String bodys1 = response1.body().string();
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = bodys1;
                        handler.sendMessage(msg);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (denglu_dialog != null) {
                denglu_dialog.dismiss();
            }
            switch (msg.what) {
                case 0:
                    ToastUtil.showToast(DengLuActivity.this, "登录成功");
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        //标识用户
                        JSONObject personObject = new JSONObject();
                        if (jsonObject.get("tel") != null) {
                            personObject.put("mobile", jsonObject.get("tel").toString());
                        } else {
                            personObject.put("mobile", "");
                        }
                        if (jsonObject.get("name") != null) {
                            personObject.put("name", jsonObject.get("name").toString());
                        } else {
                            personObject.put("name", "");
                        }
                        //添加用户唯一标示和手机号码
                        ZhugeSDK.getInstance().identify(getApplicationContext(), jsonObject.get("tel").toString(),
                                personObject);
                        //通知页面更新
                        sendBroadcast(new Intent("bei_er").putExtra("bei_er", 0));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    DengLuActivity.this.finish();
                    break;
                case 1:
                    try {
                        JSONObject jsonObject = JSONUtil.strToJson(msg.obj.toString());
                        assert jsonObject != null;
                        ToastUtil.showToast(DengLuActivity.this, jsonObject.get("error_description").toString());
                    } catch (Exception e) {
                        ToastUtil.showToast(DengLuActivity.this, "登陆失败！");
                    }
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }
}
